package com.woniuxy.controller;

import com.auth0.jwt.JWT;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.exception.UnauthorizedException;
import com.woniuxy.service.UserService;
import com.woniuxy.shiro.Utils.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @Description: TODO(用一句话描述这个类的作用)
 * @Author 18452
 * @Date 2021/5/7 18:49
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public ResponseEntity login(@RequestParam("username") String username,
                                @RequestParam("password") String password){
        //在自定义域中认证
        /*System.out.println(username+"----"+password);
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        subject.login(usernamePasswordToken);
        if (subject.isAuthenticated()) {
            return true;
        } else {
            return false;
        }*/
        if (password == null && username == null){
            return new ResponseEntity(200, "请输入账号密码", null);
        }
        //使用JWT
        //加密
        SimpleHash simpleHash = new SimpleHash("MD5", password, username);
        //获取加密后的密码
        String newPass = simpleHash.toHex();
        //通过数据库查询保存的密码
        User user = userService.selectUser(username);
        if (newPass.equals(user.getPassword())) {
            //生成token
            String sign = JWTUtil.sign(username, newPass);
            System.out.println(sign);
            return new ResponseEntity(200, "登陆成功", user);
        } else {
            throw new UnauthorizedException();
            //return new ResponseEntity(200, "账号或密码错误", null);
        }
    }

    /**
     * 如果没有携带token直接请求,会被设定为游客访问
     * @return
     */
    @GetMapping("/article")
    @ResponseBody
    public ResponseEntity article(){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            return new ResponseEntity(200, "登录成功", null);
        } else {

            return new ResponseEntity(200, "游客访问", null);
        }
    }
}
